#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'Ma'

import tornado.wsgi
import os
import torndb
import hashlib
import time
import markdown

from bae.core import const

class Application(tornado.wsgi.WSGIApplication):
    def __init__(self):
        handlers = [
            (r"/", HomeHandler),
            (r"/Ajax/(\d+)", AjaxHandler),
            (r"/Login", LoginHandler),
            (r"/Add", AddHandler),
            (r"/(\d+)", InfoHandler),
            (r"/(\d+)/Edit", EditHandler),
            (r"/(\d+)/Delete", DeleteHandler),
            (r"/Tag/(.+)", TagHandler),
        ]
        settings = dict(
            blog_title="My Blog",
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            xsrf_cookies=True,
            cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
            login_url="/Login",
            debug=True
        )
        tornado.wsgi.WSGIApplication.__init__(self, handlers, **settings)

        # 连接数据库
        self.db = torndb.Connection(
            host=const.MYSQL_HOST + ":" + const.MYSQL_PORT, database="CeXAfDiLePXDxIqbfWZe",
            user=const.MYSQL_USER, password=const.MYSQL_PASS, max_idle_time=10)


class BaseHandler(tornado.web.RequestHandler):
    @property
    def db(self):
        return self.application.db

    def get_current_user(self):
        user = self.get_secure_cookie("myname", None)
        password = self.get_secure_cookie("mypassword", None)
        if not (user and password): return None
        return self.db.get("SELECT * FROM user WHERE `name` = %s AND `password` = %s", user.strip(), password.strip())

    def get_tag(self, tags):
        """
        获取相关标签的ID
        """
        ids = []
        for i in tags:
            tag = self.db.get("SELECT * FROM `tags` WHERE `name` = %s", i.strip())
            if not tag:
                tag_id = self.db.execute("INSERT INTO tags (`name`,`date`) VALUES (%s,%s)", i.strip(), int(time.time()))
                ids.append(tag_id)
            else:
                ids.append(tag.id)
        ids = list(set(ids))  # 去除重复
        return ids

    def get_blog(self, id):
        """
        获取一个文章的详情
        """

        info = self.db.get("SELECT * FROM `blog` WHERE `id` = %s", int(id))
        if not info:
            return info

        tags_temp = []
        tags = self.db.query("SELECT * FROM `tag_to_blog` WHERE `blog_id` = %s", int(id))
        if tags:
            for i in tags:
                tags_temp.append(self.db.get("SELECT * FROM `tags` WHERE `id` = %s", i.tag_id))
        info['tags'] = tags_temp
        return info

    def get_all_tags(self, selected={}):
        """
        获取所有标签
        """
        if selected:
            selected_str = ''
            for i in selected:
                selected_str = selected_str + str(i.id) + ","
            selected_str = selected_str.strip(',')
            tags = self.db.query("SELECT * FROM `tags` WHERE `id` NOT IN (" + selected_str + ")")
        else:
            tags = self.db.query("SELECT * FROM `tags`")
        return tags

    def get_ids_by_tag(self, tag):
        """
        通过标签获取标签下所有文章的id
        """
        blog_id = []
        blog_id_temp = []
        tag_info = self.db.get("SELECT * FROM `tags` WHERE `name` = %s", tag)
        if tag_info:
            blog_id_temp = self.db.query("SELECT `blog_id` FROM `tag_to_blog` WHERE `tag_id` = %s", tag_info.id)
        for i in blog_id_temp:
            blog_id.append(i.blog_id)
        return blog_id


class HomeHandler(BaseHandler):
    """
    首页
    """

    def get(self):
        """
        自动检测是不是搜索标签的页面
        """
        blogs = self.db.query(
            "SELECT `id`,`title`,`summary`,`date`,`user_id` FROM `blog` ORDER BY `date` DESC LIMIT 30")
        self.render("index.html", blogs=blogs)


class TagHandler(BaseHandler):
    """
    搜索标签
    """

    def get(self, tag, date=''):
        tag = tag.strip()
        blog_ids = self.get_ids_by_tag(tag)
        blogs = []
        if blog_ids:
            blogs = self.db.query(
                "SELECT `id`,`title`,`summary`,`date`,`user_id` FROM `blog` WHERE `id` IN (" + ','.join(
                    str(v) for v in blog_ids) + ") ORDER BY `date` DESC LIMIT 100")
            #100条数据基本上显示完了
        self.render("tag.html", blogs=blogs)


class AjaxHandler(BaseHandler):
    """
    Ajax加载
    """

    def get(self, date):
        blogs = self.db.query(
            "SELECT `id`,`title`,`summary`,`date`,`user_id` FROM `blog` WHERE `date` < %s ORDER BY `date` DESC LIMIT 30",
            int(date))
        self.render("ajax.html", blogs=blogs)


class LoginHandler(BaseHandler):
    """
    登陆
    """

    def get(self):
        self.render("login.html")

    def post(self):
        user = self.get_argument('user')
        password = self.get_argument('password')
        password = hashlib.sha1(password.strip()).hexdigest()
        info = self.db.get("SELECT * FROM user WHERE `name` = %s AND `password` = %s", user.strip(), password)
        if info:
            self.set_secure_cookie("myname", info.name)
            self.set_secure_cookie("mypassword", info.password)
            self.redirect("/Add")
        else:
            self.redirect("/Login")


class AddHandler(BaseHandler):
    """
    添加博客
    """

    @tornado.web.authenticated
    def get(self):
        tags = self.get_all_tags()
        self.render("add.html", tags=tags)

    @tornado.web.authenticated
    def post(self):
        title = self.get_argument('title')
        content = self.get_argument('content')
        tag = self.get_arguments('tag', [])
        new_tag = self.get_argument('new_tag', None)
        #标题和内容至少有一个
        if not (title and content):
            self.redirect("/Add")

        tag_ids = None

        if new_tag:
            tag.append(new_tag)
        if len(tag):
            tag_ids = self.get_tag(tag)
        summary = markdown.markdown(content[0:140])
        html = markdown.markdown(content)
        blog_id = self.db.execute(
            "INSERT INTO blog (`title`,`content`,`html`,`summary`,`date`,`user_id`) VALUES (%s,%s,%s,%s,%s,%s)",
            title[0:100].strip(), content.strip(), html.strip(), summary.strip(), int(time.time()),
            self.get_current_user().id)
        #写入标签
        if tag_ids:
            for i in tag_ids:
                self.db.execute("INSERT INTO tag_to_blog (`tag_id`,`blog_id`) VALUES (%s,%s)", i, int(blog_id))
        if blog_id:
            self.redirect('/' + str(blog_id))
        else:
            #失败了
            self.redirect("/Add")


class EditHandler(AddHandler):
    """
    编辑一个博客的时候
    """

    @tornado.web.authenticated
    def get(self, blog_id):
        info = self.get_blog(blog_id)
        tags = self.get_all_tags(info.tags)
        self.render("edit.html", info=info, tags=tags, blog_id=blog_id)


    @tornado.web.authenticated
    def post(self, blog_id):
        if not blog_id:
            blog_id = self.get_argument('blog_id')
        title = self.get_argument('title')
        content = self.get_argument('content')
        tag = self.get_arguments('tag', [])
        new_tag = self.get_argument('new_tag', None)
        #标题和内容至少有一个
        if not (title and content):
            self.redirect("/" + blog_id + "/Edit")

        tag_ids = []

        if new_tag:
            tag.append(new_tag)
        if len(tag):
            tag_ids = self.get_tag(tag)
        summary = markdown.markdown(content[0:140])
        html = markdown.markdown(content)
        r = self.db.execute_rowcount(
            "UPDATE blog SET `title`=%s,`content`=%s,`html`=%s,`summary`=%s,`last_modify_date`=%s,`user_id`=%s "
            "WHERE id=%s",
            title.strip(), content.strip(), html, summary.strip(), int(time.time()), self.get_current_user().id,
            blog_id)
        #写入标签
        if r:
            self.db.execute("DELETE FROM tag_to_blog WHERE `blog_id` = %s", int(blog_id))  # 先删除所有老的标签
            if len(tag_ids):
                for i in tag_ids:
                    self.db.execute("INSERT INTO tag_to_blog (`tag_id`,`blog_id`) VALUES (%s,%s)", i, int(blog_id))

            #成功了，跳到展示页面
            self.redirect('/' + blog_id)
        else:
            #失败了继续编辑
            self.redirect("/" + blog_id + "/Edit")


class DeleteHandler(BaseHandler):
    """
    删除一个博客
    """

    @tornado.web.authenticated
    def get(self, blog_id):
        r = self.db.execute_rowcount("DELETE FROM blog WHERE `id` = %s", int(blog_id))
        if r:
            self.redirect('/')
        else:
            #失败了
            self.redirect("/" + blog_id)


class InfoHandler(BaseHandler):
    """
    查看一个博客
    """

    def get(self, blog_id):
        info = self.get_blog(blog_id)
        self.render("info.html", info=info, blog_id=blog_id)


from bae.core.wsgi import WSGIApplication

application = WSGIApplication(Application())